// ConsoleApplication3.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <fstream>
#include <vector>
#include <CGAL/Simple_cartesian.h>
#include <CGAL/linear_least_squares_fitting_3.h>

typedef double                      FT;
typedef CGAL::Simple_cartesian<FT>  K;
typedef K::Line_3                   Line;
typedef K::Plane_3                  Plane;
typedef K::Point_3                  Point;
typedef K::Triangle_3               Triangle;
typedef K::Direction_3				Direction;

bool ReadTestFile(const std::string& strFileName, std::vector<K::Point_3>& pts)
{
	//  打开文件
	std::ifstream f(strFileName, std::ios::binary);
	if (!f.is_open())
	{
		std::cout << "未成功打开文件\n";
		return false;
	}

	//  读文件
	std::string line;
	getline(f, line);	//	第一行为参考结果，不作处理

	while (getline(f, line))
	{
		//  逐行读
		std::istringstream iss(line);
		float x = 0, y = 0, z = 0;
		iss >> x >> y >> z;

		pts.push_back(K::Point_3(x, y, z));
	}

	//  关闭文件
	f.close();

	return true;
}

void dump(const Point& pt)
{
	std::cout << "\tPoint(" << pt.x() << ", " << pt.y() << ", " << pt.z() << ")";
}

void dump(const Direction& dir)
{
	std::cout << "\tDirection(" << dir.dx() << ", " << dir.dy() << ", " << dir.dz() << ")";
}

void dump(const Line & line)
{
	std::cout << "[line]\n";

	dump(line.point());
	dump(line.direction());

	std::cout << std::endl;
}

void dump(const Plane & plane)
{
	std::cout << "[Plane]\n";

	dump(plane.point());
	dump(plane.orthogonal_direction());

	std::cout << std::endl;
}

void test_linefit(const std::string& filename)
{
	std::vector<Point> points;
	if (!ReadTestFile(filename, points))
		return;

	Line line;
	linear_least_squares_fitting_3(points.begin(), points.end(), line, CGAL::Dimension_tag<0>());

	dump(line);
}

void test_planefit(const std::string& filename)
{
	std::vector<Point> points;
	if (!ReadTestFile(filename, points))
		return;

	Plane plane;
	linear_least_squares_fitting_3(points.begin(), points.end(), plane, CGAL::Dimension_tag<0>());

	dump(plane);
}

void main()
{
	//	test_linefit("d:/data/line.txt");
	test_planefit("d:/data/plane.txt");
}